import { onMounted, ref, isReactive, toRaw } from "vue";
import type { TableOptions, IQuery } from "./types";

export function useTable({ query, queryApi, autoLoad = true }: TableOptions) {
  const commonQuery: IQuery = {
    pageSize: query.pageSize || 10,
    currentPage: query.currentPage || 1
  };

  Object.assign(query, commonQuery);
  const initQuery = JSON.parse(JSON.stringify(query));

  const dataList = ref<any[]>([]);
  const total = ref(0);
  const loading = ref(false);

  const getListAsync = async () => {
    loading.value = true;
    try {
      const { content, code } = await queryApi(
        isReactive(query) ? toRaw(query) : query
      );
      loading.value = false;
      if (code === "00000") {
        total.value = content.total;
        dataList.value = content.dataList;
      }
    } catch (error) {
      loading.value = false;
    }
  };

  const onSearch = () => {
    query.currentPage = 1;
    getListAsync();
  };

  const reset = async () => {
    Object.assign(query, initQuery);
    onSearch();
  };

  const handleSizeChange = (val: number) => {
    query.pageSize = val;
    onSearch();
  };

  const handleCurrentChange = (val: number) => {
    query.currentPage = val;
    getListAsync();
  };

  const selectItems = ref([]);
  const handleSelectionChange = (val, cb) => {
    selectItems.value = val;
    cb && cb();
  };

  const onSelectionCancel = cb => {
    selectItems.value = [];
    cb && cb();
  };

  onMounted(() => {
    if (autoLoad) {
      getListAsync();
    }
  });

  return {
    dataList,
    total,
    loading,
    selectItems,
    getListAsync,
    onSearch,
    reset,
    handleCurrentChange,
    handleSizeChange,
    handleSelectionChange,
    onSelectionCancel
  };
}
